package com.ErpCoreWeb.Database.Table;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CColumnEnumVal;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.ColumnType;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreWeb.Common.EditObject;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class Edit
 */
@WebServlet("/Database_Table_Edit")
public class Edit extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

	public CUser m_User = null;
    public CTable m_Table = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Edit() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User=(CUser)request.getSession().getAttribute("User");
        if (!m_User.IsRole("管理员"))
        {
        	try {
				response.getWriter().print("没有管理员权限！");
	        	response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	return ;
        }

		try {
			String id = request.getParameter("id");
			if (Global.IsNullParameter(id)) {
				response.getWriter().print("请选择表！");
				response.getWriter().close();
				return;
			}

			m_Table = (CTable) Global.GetCtx(this.getServletContext())
					.getTableMgr().Find(Util.GetUUID(id));
			if (m_Table == null) {
				response.getWriter().print("表不存在！");
				response.getWriter().close();
			}
			// 保存到编辑对象
			EditObject.Add(request.getSession().getId(), m_Table);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
            GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
            PostData();
            //从编辑对象移除
            EditObject.Remove(request.getSession().getId(), m_Table);
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
            m_Table.Cancel();
            return ;
        }
	}
    void GetData()
    {

        String sData = "";
        List<CBaseObject> lstObj = m_Table.getColumnMgr().GetList();
        for (CBaseObject obj : lstObj)
        {
            CColumn col = (CColumn)obj;
            String sRefTableName = "", sRefColName = "", sRefShowColName = "", sEnumVal = "";
            if (!col.getRefTable().equals(Util.GetEmptyUUID()))
            {
                CTable refTable = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(col.getRefTable());
                if (refTable != null)
                {
                    sRefTableName = refTable.getName();
                    if (!col.getRefCol().equals(Util.GetEmptyUUID()))
                    {
                        CColumn refCol = (CColumn)refTable.getColumnMgr().Find(col.getRefCol());
                        if (refCol != null)
                            sRefColName = refCol.getName();
                        CColumn refShowCol = (CColumn)refTable.getColumnMgr().Find(col.getRefShowCol());
                        if (refShowCol != null)
                            sRefShowColName = refShowCol.getName();
                    }
                }
            }
            List<CBaseObject> lstObjEV = col.getColumnEnumValMgr().GetList();
            for (CBaseObject objEV : lstObjEV)
            {
                CColumnEnumVal ev = (CColumnEnumVal)objEV;
                sEnumVal += ev.getVal() + "/";
            }
            if(sEnumVal.endsWith("/"))
            	sEnumVal=sEnumVal.substring(0,sEnumVal.length()-1);

            sData += String.format("{ \"id\": \"%s\",\"Name\":\"%s\", \"Code\":\"%s\", \"ColType\":\"%s\", \"ColLen\":\"%d\",\"AllowNull\":\"%d\",\"IsSystem\":\"%d\",\"DefaultValue\":\"%s\",\"ColDecimal\":\"%d\",\"Formula\":\"%s\",\"RefTable\":\"%s\",\"RefTableName\":\"%s\",\"RefCol\":\"%s\",\"RefColName\":\"%s\",\"RefShowCol\":\"%s\",\"RefShowColName\":\"%s\",\"EnumVal\":\"%s\",\"IsUnique\":\"%d\" },"
                , col.getId().toString(), col.getName(), col.getCode(), CColumn.ConvertColTypeToString(col.getColType()), col.getColLen(), col.getAllowNull() ? 1 : 0, col.getIsSystem() ? 1 : 0, col.getDefaultValue(), col.getColDecimal(), col.getFormula(), col.getRefTable().toString(), sRefTableName, col.getRefCol().toString(), sRefColName, col.getRefShowCol().toString(), sRefShowColName, sEnumVal, col.getIsUnique() ? 1 : 0);
        }
        if(sData.endsWith(","))
        	sData=sData.substring(0,sData.length()-1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, 5);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

	void PostData() {
		try {
			String Name = request.getParameter("Name");
			String Code = request.getParameter("Code");
			String IsSystem = request.getParameter("IsSystem");
			String GridData = request.getParameter("GridData");

			CUser user = (CUser) request.getSession().getAttribute("User");

			if (Global.IsNullParameter(Name) || Global.IsNullParameter(Code)) {
				response.getWriter().print("数据不完整！");
				return;
			} else {
				if (!m_Table.getName().equalsIgnoreCase(Name)
						&& Global.GetCtx(this.getServletContext())
								.getTableMgr().FindByName(Name) != null) {
					response.getWriter().print("相同名称的表已经存在！");
					return;
				}
				if (!m_Table.getCode().equalsIgnoreCase(Code)
						&& Global.GetCtx(this.getServletContext())
								.getTableMgr().FindByCode(Code) != null) {
					response.getWriter().print("相同编码的表已经存在！");
					return;
				}

				m_Table.setName(Name);
				m_Table.setCode(Code);
				m_Table.setIsSystem(IsSystem.equals("1") ? true : false);
				m_Table.setIsFinish(true);
				m_Table.setUpdator(user.getId());

				// 自定义字段
				int iLastIdx = 4;
				String[] arr1 = GridData.split(";");
				Map<UUID, UUID> sortColID = new HashMap<UUID, UUID>();
				for (String str1 : arr1) {
					if (str1.length() == 0)
						continue;
					iLastIdx++;

					String[] arr2 = str1.split(",");
					UUID guidID = Util.GetUUID(arr2[0]);
					if (sortColID.containsKey(guidID))
						continue;

					sortColID.put(guidID, guidID);
					CColumn col = (CColumn) m_Table.getColumnMgr().Find(guidID);
					if (col == null) {
						col = new CColumn();
						col.Ctx = m_Table.Ctx;
						col.setFW_Table_id(m_Table.getId());
						col.setId(guidID);
						col.setCreator(user.getId());
						m_Table.getColumnMgr().AddNew(col);
					} else {
						col.setUpdator(user.getId());
						m_Table.getColumnMgr().Update(col);
					}
					col.setName(arr2[1]);
					col.setCode(arr2[2]);
					col.setColType(CColumn.ConvertStringToColType(arr2[3]));
					col.setColLen(Integer.valueOf(arr2[4]));
					col.setAllowNull((arr2[5].equals("1")) ? true : false);
					col.setIsSystem((arr2[6].equals( "1")) ? true : false);
					col.setIsUnique((arr2[17].equals( "1")) ? true : false);
					col.setIsVisible(true);
					col.setDefaultValue(arr2[7]);
					col.setColDecimal((arr2[8].length()>0) ? Integer
							.valueOf(arr2[8]) : 0);
					col.setFormula(arr2[9]);
					if (col.getColType() == ColumnType.ref_type) {
						col.setRefTable(Util.GetUUID(arr2[10]));
						col.setRefCol(Util.GetUUID(arr2[12]));
						col.setRefShowCol(Util.GetUUID(arr2[14]));
					}
					if (arr2[16].trim().length() > 0) {
						col.getColumnEnumValMgr().RemoveAll();
						String[] arrEnum = arr2[16].trim().split("/");
						for (int i = 0; i < arrEnum.length; i++) {
							String sEnumVal = arrEnum[i];
							CColumnEnumVal ev = new CColumnEnumVal();
							ev.Ctx = col.Ctx;
							ev.setFW_Column_id(col.getId());
							ev.setVal(sEnumVal);
							ev.setIdx(i);
							col.getColumnEnumValMgr().AddNew(ev);
						}
					}
					col.setIdx(iLastIdx);
				}
				// 要删除的字段
				Map<UUID, UUID> sortOldColID = new HashMap<UUID, UUID>();
				List<CBaseObject> lstOldCol = m_Table.getColumnMgr().GetList();
				for (CBaseObject objOld : lstOldCol) {
					CColumn col = (CColumn) objOld;
					if (col.getCode().equalsIgnoreCase("id")
							|| col.getCode().equalsIgnoreCase("Created")
							|| col.getCode().equalsIgnoreCase("Creator")
							|| col.getCode().equalsIgnoreCase("Updated")
							|| col.getCode().equalsIgnoreCase("Updator"))
						continue;
					sortOldColID.put(objOld.getId(), objOld.getId());
				}
				for (Map.Entry<UUID, UUID> pair : sortOldColID.entrySet()) {
					if (!sortColID.containsKey(pair.getKey()))
						m_Table.getColumnMgr().Delete(pair.getKey());
				}
				//

				Global.GetCtx(this.getServletContext()).getTableMgr()
						.Update(m_Table);

				if (!CTable.CreateDataTable(m_Table)) {
					response.getWriter().print("创建表失败！");
					return;
				}
				if (!Global.GetCtx(this.getServletContext()).getTableMgr()
						.Save(true)) {
					response.getWriter().print("修改失败！");
					return;
				}

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
